package com.master.demo.im.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.master.common.api.IPageInfo;
import com.master.common.api.Query;
import com.master.common.api.ResponseInfo;
import com.master.common.constant.StringPoolConstant;
import com.master.common.exception.ErrorException;
import com.master.common.utils.DozerUtil;
import com.master.common.utils.RandomUtil;
import com.master.common.validator.ValidatorUtil;
import com.master.demo.im.mapper.SessionListMapper;
import com.master.demo.im.mapper.SessionMessageMapper;
import com.master.demo.im.pojo.command.SessionListCommand;
import com.master.demo.im.pojo.entity.SessionList;
import com.master.demo.im.pojo.vo.SessionListVO;
import com.master.demo.im.pojo.vo.SessionMessageVO;
import com.master.demo.im.service.ISessionListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 会话列 服务实现类
 *
 * @author: Yang
 * @date: 2022-08-09
 * @version: 1.0.0
 * Copyright Ⓒ 2021 恒翔 Computer Corporation Limited All rights reserved.
 */
@Service
public class SessionListServiceImpl extends ServiceImpl<SessionListMapper, SessionList> implements ISessionListService {
    @Autowired
    private SessionListMapper sessionListMapper;
    @Autowired
    private SessionMessageMapper sessionMessageMapper;

    /**
     * 根据id获取会话列信息
     *
     * @param id 会话列id
     * @return
     */
    private SessionList getSessionList(Long id) {
        SessionList sessionList = sessionListMapper.selectById(id);
        if (ValidatorUtil.isNull(sessionList)) {
            throw new ErrorException("会话列信息不存在，无法操作");
        }
        return sessionList;
    }

    @Override
    public ResponseInfo<IPageInfo<SessionListVO>> pageSessionList(Query query) {
        IPage<SessionListVO> iPage = sessionListMapper.pageSessionList(new Page<>(query.getCurrent(), query.getSize()), query);
        return ResponseInfo.success(new IPageInfo(iPage.getCurrent(), iPage.getSize(), iPage.getTotal(), iPage.getRecords()));
    }

    @Override
    public ResponseInfo<List<SessionListVO>> listSessionList(Query query) {
        List<SessionListVO> result = sessionListMapper.listSessionList(query);
        result.stream().forEach(v -> {
            SessionMessageVO sessionMessage = sessionMessageMapper.getLastMessage(query);
            v.setLastMessageTime(Optional.ofNullable(sessionMessage).map(d -> d.getTime()).orElse(StringPoolConstant.EMPTY));
        });
        return ResponseInfo.success(result);
    }

    @Override
    public ResponseInfo<SessionListVO> getSessionListById(Long id) {
        return ResponseInfo.success(DozerUtil.convertor(getSessionList(id), SessionListVO.class));
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "masterTransactionManager")
    public ResponseInfo saveSessionList(SessionListCommand command) {
        String number = RandomUtil.randomNumbers(8);
        saveSessionList(command.getSender(), command.getReceiver(), number);
        saveSessionList(command.getReceiver(), command.getSender(), number);
        return ResponseInfo.success();
    }

    /**
     * 生成会话列表
     *
     * @param sender   发送人
     * @param receiver 接收人
     */
    private void saveSessionList(String sender, String receiver, String number) {
        SessionList sessionList = sessionListMapper.getSessionBySenderAndReciver(sender, receiver);
        if (ValidatorUtil.isNotNull(sessionList)) {
            if (sessionList.getDeleted() == 1) {
                sessionList.setDeleted(0);
                sessionListMapper.updateById(sessionList);
            }
        } else {
            sessionList = new SessionList().setSender(sender).setReceiver(receiver).setNumber(number);
            sessionListMapper.insert(sessionList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "masterTransactionManager")
    public ResponseInfo updateSessionList(SessionListCommand command) {
        SessionList sessionList = getSessionList(command.getId());
        DozerUtil.convertor(command, sessionList);
        sessionListMapper.updateById(sessionList);
        return ResponseInfo.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "masterTransactionManager")
    public ResponseInfo removeSessionListByIds(List<Long> ids) {
        sessionListMapper.deleteBatchIds(ids);
        return ResponseInfo.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "masterTransactionManager")
    public ResponseInfo removeSessionListById(Long id) {
        sessionListMapper.deleteById(id);
        return ResponseInfo.success();
    }

}
